package cs.android;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;

import cs.android.viewbase.ContextPresenter;


import static cs.java.lang.Lang.error;

import android.os.Environment;
import cs.android.lang.AndroidLang;
import cs.android.lang.Application;

public abstract class ApplicationBase extends ContextPresenter implements Application,
		UncaughtExceptionHandler {

	public ApplicationBase() {
		super(ApplicationContext.getContext());
		Thread.currentThread().setUncaughtExceptionHandler(this);
		AndroidLang.setApplication(this);
	}

	private void writeExceptionToSdlogFile(Throwable ex) {
		String path = Environment.getExternalStorageDirectory() + "/" + getApplicationName();
		PrintWriter writer;
		try {
			writer = new PrintWriter(new FileWriter(path + ".log", true));
			ex.printStackTrace(writer);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void logException(Throwable e) {
		writeExceptionToSdlogFile(e);
	}

	public void uncaughtException(Thread thread, final Throwable ex) {
		error(ex);
		logException(ex);
	}
}
